import { reactive } from 'vue'
import { format } from 'date-fns'
import { parseTime } from '@/common/common'
import { TaskDefinedLog } from '@/service/modules/task-manage/types'
import { delTaskLogReq, findTaskLogsReq } from '@/service/modules/task-manage'

export function useTable() {
  const state = reactive({
    taskDefinedId: 0,
    switchVersionFunc: (id: number) => {},
    list: [],
    loading: false,
    currentRecord: {} as TaskDefinedLog
  })

  const getList = async () => {
    if (state.loading) return
    state.loading = true

    const res = await findTaskLogsReq({ taskDefinedId: state.taskDefinedId })
    state.loading = false
    if (!res.data) throw Error()
    state.list = res.data.map((record: TaskDefinedLog) => {
      record.createTime = record.createTime
        ? format(parseTime(record.createTime), 'yyyy-MM-dd HH:mm:ss')
        : ''
      record.updateTime = record.updateTime
        ? format(parseTime(record.updateTime), 'yyyy-MM-dd HH:mm:ss')
        : ''
      return record
    })
  }

  const delVersion = (id: number, version: number) => {
    window.$dialog.warning({
      title: window.$t('dialog.warningTitle'),
      content: window.$t('taskManage.delVersionTips') + version,
      positiveText: window.$t('dialog.positiveText'),
      negativeText: window.$t('dialog.negativeText'),
      onPositiveClick: async () => {
        const res = await delTaskLogReq({ taskLogId: id })
        if (res.resp_code === 0) {
          getList()
        }
      }
    })
  }

  const switchVersion = (id: number) => {
    window.$dialog.warning({
      title: window.$t('dialog.warningTitle'),
      content: window.$t('taskManage.switchVersionTips'),
      positiveText: window.$t('dialog.positiveText'),
      negativeText: window.$t('dialog.negativeText'),
      onPositiveClick: () => {
        state.switchVersionFunc(id)
      }
    })
  }
  const onOperationClick = (
    data: { rowData: TaskDefinedLog },
    type: 'switchVersion' | 'delVersion'
  ) => {
    state.currentRecord = data.rowData
    switch (type) {
      case 'switchVersion':
        switchVersion(data.rowData.id)
        break
      case 'delVersion':
        delVersion(data.rowData.id, data.rowData.version)
        break
    }
  }

  return {
    state,
    onOperationClick,
    getList
  }
}
